<template>
  <div class="buttonListComponent" v-if="item">
    <draggable
      class="vlonButtonGroupWrapper"
      v-model="buttons"
      handle=".el-icon-rank"
      v-bind="ButtonSwiperOptions"
      @end="listButtonSwiperOptionsChange"
      v-if="buttons && buttons.length > 0"
    >
      <transition-group tag="ul" class="list">
        <li
          class="vlonButtonGroupItem"
          v-for="(cl, clIndex) in buttons"
          :key="cl.id"
          :data-id="cl.id"
        >
          <i class="el-icon-rank"></i>

          <div class="rightWrapper">
            <div class="item">
              <span class="title">按钮图片：</span>
              <div class="right">
                <div class="buttonWrapper">
                  <div
                    class="uploadBtn"
                    v-if="!cl.imgUrl"
                    @click="addChooseImg(clIndex)"
                  >
                    <i class="el-icon-plus"></i>
                  </div>
                  <img
                    v-if="cl.imgUrl != '' && cl.imgUrl.indexOf('icon-') == -1"
                    :src="cl.imgUrl"
                    alt
                  />
                  <i
                    v-if="cl.imgUrl && cl.imgUrl.indexOf('icon-') > -1"
                    :class="cl.imgUrl"
                    style="width: 100%; display: flex; justify-content: center"
                  ></i>
                  <span
                    v-if="cl.imgUrl != ''"
                    class="repaceImg"
                    @click="updateChooseImg(clIndex)"
                    >替换</span
                  >
                  <span
                    v-if="cl.imgUrl != ''"
                    class="el-icon-error delImg"
                    @click="rightListButtonSwiperDelImg(clIndex)"
                  ></span>
                </div>
                <p class="tips">建议图片尺寸为200x200，比例为1:1</p>
              </div>
            </div>
            <div class="item">
              <span class="title">按钮文字：</span>
              <div class="right">
                <el-input
                  v-model="cl.name"
                  maxlength="5"
                  show-word-limit
                  clearable
                  @input="buttonTextChange(clIndex)"
                ></el-input>
              </div>
            </div>
            <div class="item">
              <span class="title">跳转链接：</span>
              <div class="right">
                <div class="chooseUrl">
                  <div class="urlBox">
                    <div class="haveUrl" v-if="cl.linkName || cl.linkUrl">
                      <el-button plain disabled class="haveUrlBtn">
                        <i class="el-icon-paperclip"></i>
                        <span>{{ cl.linkName || cl.linkUrl || "" }}</span>
                      </el-button>
                      <el-button
                        type="text"
                        class="updateHref"
                        @click="updateLinkHref(clIndex)"
                        >修改</el-button
                      >
                    </div>
                    <div class="noUrl" v-else>
                      <el-button
                        plain
                        class="noUrlBtn"
                        @click="addLinkHref(clIndex)"
                      >
                        <i class="el-icon-paperclip"></i>
                        选择链接
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <span
            class="el-icon-error delButtonSwiperItem"
            v-if="buttons.length > item.min"
            @click="listButtonSwiperdelButtonSwiperItem(cl.id)"
          ></span>
        </li>
      </transition-group>
    </draggable>

    <el-button
      style="width: 100%"
      v-if="buttons && buttons.length < item.max"
      size="small"
      @click="listButtonSwiperAddButtonSwiperItem"
      >+添加图片 ({{ buttons.length }}/{{ item.max }})</el-button
    >
  </div>
</template>

<script>
import { mapState } from "vuex";
import Bus from "@/utils/bus";
import buttonIcon from "@/assets/images/decorate/buttonIcon.png";
import draggable from "vuedraggable";
export default {
  name: "buttonListComponent",
  data() {
    return {
      buttons: null,
      currentIndex: 0,
      buttonIcon,
      ButtonSwiperOptions: {
        group: { name: "layout", pull: false, put: false },
        draggable: ".vlonButtonGroupItem",
        forceFallback: true,
        sort: true,
        animation: 300,
      },
      needUpdate: true,
    };
  },
  props: ["item", "rightIndex", "catalogIndex", "id"],
  components: { draggable },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.init();
      setTimeout(() => {
        this.needUpdate = false;
      }, 1000);
    });
    
    Bus.$off(`buttonListChooseAfter${this.id}`);
    Bus.$on(`buttonListChooseAfter${this.id}`, (params) => {
      this.buttons[this.currentIndex].imgUrl = params.url;
      this.updateData();
    });

    Bus.$off(`buttonListChooseLinkAfter${this.id}`);
    Bus.$on(`buttonListChooseLinkAfter${this.id}`, (params) => {
      this.buttons[this.currentIndex].linkUrl = params.url;
      this.buttons[this.currentIndex].linkName = params.name;
      this.updateData();
    });
    // Bus.$off(`buttonListRadioUpdate${this.id}`);
    // Bus.$on(`buttonListRadioUpdate${this.id}`, (numbers) => {
    //   if (numbers < this.buttons.length) {
    //     let cha = this.buttons.length - numbers;
    //     this.buttons.pop();
    //     if (cha > 1) {
    //       this.buttons.pop();
    //     }
    //   } else if (numbers > this.buttons.length) {
    //     let cha = numbers - this.buttons.length;
    //     this.buttons.push({
    //       id: "vlonButtonGroupItemId_" + new Date().getTime(),
    //       imgUrl: this.buttonIcon,
    //       name: "按钮文字",
    //       default: this.buttonIcon,
    //       linkUrl: "",
    //       linkName: "",
    //     });
    //     if (cha > 1) {
    //       this.buttons.push({
    //         id: "vlonButtonGroupItemId_" + new Date().getTime(),
    //         imgUrl: this.buttonIcon,
    //         name: "按钮文字",
    //         default: this.buttonIcon,
    //         linkUrl: "",
    //         linkName: "",
    //       });
    //     }
    //   }
    //   this.updateData();
    // });
  },
  methods: {
    init() {
      if (this.item) {
        this.buttons = null;
        this.$nextTick(() => {
          let oItem = JSON.parse(JSON.stringify(this.item));
          this.buttons = JSON.parse(JSON.stringify(oItem.list));
        });
      }
    },
    //同时更新主视图区域中的数据
    updateData(params) {
      //标识是否需要更新Main中的子组件
      let needUpdateMainChild = true;
      if (params !== undefined && params !== null) {
        needUpdateMainChild = params.needUpdateMainChild;
      }
      // console.log(this.buttons,this.item.ename);
      //更新给直属父级
      this.$emit(
        "updateParent",
        JSON.stringify({
          value: JSON.stringify(this.buttons),
          ename: this.item.ename,
          rightIndex: this.rightIndex,
          catalogIndex: this.catalogIndex,
          needUpdateMainChild: needUpdateMainChild,
          needUpdateMain: false,
        })
      );
    },
    //右侧 轮播图组件 拖拽 改变顺序 后触发的事件
    listButtonSwiperOptionsChange() {
      //同时改变主视图区域中的数据
      const buttons = JSON.stringify(this.buttons);
      this.buttons = null;
      this.buttons = JSON.parse(buttons);
      this.$nextTick(() => {
        this.updateData();
      });
    },
    //在右侧，为轮播图组件 (点击) 选择 图片
    addChooseImg(index) {
      this.currentIndex = index;
      Bus.$emit("openChooseImgGroup", { ename: "buttonList", controlid: this.id, });
    },
    //在右侧，为轮播图组件 (点击) 选择 图片
    updateChooseImg(index) {
      this.currentIndex = index;
      Bus.$emit("openChooseImgGroup", { ename: "buttonList", controlid: this.id });
    },

    //在右侧轮播图组件中，点击删除图片，回到待上传图片的场景
    rightListButtonSwiperDelImg(index) {
      this.buttons[index].imgUrl = "";
      //同时更新主视图区域中的数据
      this.updateData();
    },
    //在右侧，点击修改图片的跳转链接
    updateLinkHref(index) {
      this.currentIndex = index;
      Bus.$emit("openChooseLinkGroup", {
        name: "buttonListChooseLink",
        controlid: this.id,
        linkUrl: this.buttons[index].linkUrl,
        linkName: this.buttons[index].linkName,
      });
      //打开后回写弹窗中选中状态，现在没有唯一id无法定位到确定项,所以暂时搁置-----------
    },
    //在右侧，点击增加图片的跳转链接
    addLinkHref(index) {
      this.currentIndex = index;
      Bus.$emit("openChooseLinkGroup", { name: "buttonListChooseLink", controlid: this.id });
      //打开后初始化弹窗中选中状态，现在没有唯一id无法定位到确定项,所以暂时搁置-----------
    },
    //点击 为轮播图组件  内容模块 删除 一个按钮
    listButtonSwiperdelButtonSwiperItem(id) { 
      // console.log("id: ",id);
      this.buttons = this.buttons.filter((row) => row.id != id);
      //同时更新主视图区域中的数据
      this.updateData({ needUpdateMainChild: true, });
    },
    //点击 为轮播图组件  内容模块 追加 图片
    listButtonSwiperAddButtonSwiperItem() {
      this.buttons.push({
        id: "vlonButtonGroupItemId_" + new Date().getTime(),
        imgUrl: this.buttonIcon,
        name: "按钮文字",
        default: this.buttonIcon,
        linkUrl: "",
        linkName: "",
      });
      Bus.$emit("buttonListUpdateNumbers", this.buttons.length);
      //同时更新主视图区域中的数据
      this.updateData();
      // let ri = this.rightIndex;
      // let ci = this.catalogIndex;
      // let controls = this.decorate.controls;
      // //更新中间主区域-按钮展示数量
      // controls[this.controlsIndex].main.numberOfLines = this.oItem.list.length;
      // //更新右侧-内容-按钮列表
      // controls[this.controlsIndex].right[ri].catalog[ci] = JSON.parse(
      //   JSON.stringify(this.oItem)
      // );

      // //更新右侧-组件样式-按钮数量，更新选项
      // controls[this.controlsIndex].right.forEach((r) => {
      //   if (r.name == "组件样式") {
      //     r.catalog.forEach((c) => {
      //       if (c.ename == "numberOfLines") {
      //         for (let i = 0; i < c.options.length; i++) {
      //           if (c.options[i].value == this.oItem.list.length) {
      //             c.value = c.options[i].id;
      //             c.default = c.options[i].id;
      //             break;
      //           }
      //         }
      //       }
      //     });
      //   }
      // });
      // this.$store.dispatch("controls", controls);
      // //同时更新主视图区域中的数据
      // const ename = controls[this.controlsIndex].right[ri].catalog[ci].ename;
      // Bus.$emit(`updateMainChild${this.controlid}`, {
      //   ename: ename,
      //   value: JSON.parse(JSON.stringify(this.oItem.list)),
      // });
      // Bus.$emit(`updateRight${this.controlid}`);
      // //通知右侧-组件样式-按钮数量，更新选项
      // Bus.$emit("updateRightRadioGroup");
    },
    //按钮文字内容变更时触发
    buttonTextChange(index) {
      //同时更新主视图区域中的数据
      this.updateData();
    },
  },
  computed: mapState(["decorate"]),
  watch: {},
};
</script>

<style scoped lang="scss">
.buttonListComponent {
  .vlonButtonGroupItem {
    display: flex;
    position: relative;
    background: #f4f6f8;
    border-radius: 2px;
    box-sizing: border-box;
    border: 1px solid #e9edef;
    margin-bottom: 10px;
    align-items: center;
    padding: 10px 10px;
    & > i {
      margin-right: 10px;
    }
    .rightWrapper {
      display: flex;
      flex-direction: column;
      padding-left: 10px;
      box-sizing: border-box;
      .item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;
        .title {
          font-size: 12px;
          width: 70px;
          display: flex;
          padding-right: 10px;
          min-height: 36px;
          align-items: center;
          box-sizing: border-box;
        }
        .right {
          width: calc(100% - 70px);
          display: flex;
          .buttonWrapper {
            position: relative;
            display: flex;
            align-items: center;
            height: 40px;
            background-color: #fff;
            margin-right: 10px;
            width: 40px;
            .uploadBtn {
              width: 100%;
              height: 100%;
              display: flex;
              box-sizing: border-box;
              border-radius: 2px;
              justify-content: center;
              align-items: center;
              background-color: #fff;
              flex-direction: column;
              position: relative;
              cursor: pointer;
              border: 1px solid #e9edef;
              i {
                color: #0079fe;
                font-weight: bold;
                font-size: 14px;
                margin-top: 5px;
                margin-bottom: 5px;
              }
            }
            img {
              width: 100%;
              height: 100%;
              display: flex;
            }
            .repaceImg,
            .delImg {
              position: absolute;
              z-index: 3;
              opacity: 0.5;
              display: none;
              cursor: pointer;
              &:hover {
                cursor: pointer;
              }
            }
            .repaceImg {
              left: 0;
              bottom: 0px;
              width: 100%;
              height: 20px;
              font-size: 12px;
              background-color: rgba(0, 0, 0, 0.8);
              color: #fff;
              justify-content: center;
            }
            .delImg {
              right: -4px;
              top: -4px;
            }
            &:hover {
              .repaceImg,
              .delImg {
                display: flex;
              }
            }
          }
          p.tips {
            display: block;
            font-family: "PingFang SC";
            font-style: normal;
            font-weight: normal;
            font-size: 12px;
            line-height: 18px;
            color: #939799;
            margin-top: 8px;
          }
          .chooseUrl {
            display: flex;
            flex: 1;
            flex-direction: column;
            .urlBox {
              .haveUrl {
                position: relative;
                .haveUrlBtn {
                  padding: 0;
                  height: 32px;
                  width: 100%;
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                  padding-left: 30px;
                  box-sizing: border-box;
                  position: relative;
                  i {
                    border-right: 1px solid transparent;
                    height: 32px;
                    display: flex;
                    box-sizing: border-box;
                    align-items: center;
                    justify-content: center;
                    position: absolute;
                    width: 30px;
                    top: 0;
                    left: 0;
                    z-index: 2;
                  }
                  &:hover {
                    i {
                      border-color: #eee;
                    }
                  }
                }

                .updateHref {
                  padding: 0;
                  position: absolute;
                  top: 0;
                  right: 0;
                  z-index: 2;
                  height: 32px;
                  display: flex;
                  align-items: center;
                  width: 60px;
                  justify-content: center;
                  border-radius: 0;
                  border-left: 1px solid #eee;
                }
              }
              .noUrl {
                .noUrlBtn {
                  padding: 0;
                  height: 32px;
                  width: 100%;
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                  padding-left: 30px;
                  box-sizing: border-box;
                  position: relative;
                  i {
                    height: 32px;
                    display: flex;
                    box-sizing: border-box;
                    align-items: center;
                    justify-content: center;
                    position: absolute;
                    width: 30px;
                    top: 0;
                    left: 0;
                    z-index: 2;
                  }
                }
              }
            }
          }
        }
      }
    }

    .delButtonSwiperItem {
      position: absolute;
      top: -4px;
      right: -4px;
      z-index: 2;
      display: none;
      opacity: 0.5;
      cursor: pointer;
      &:hover {
        cursor: pointer;
      }
    }
    &:hover {
      .delButtonSwiperItem {
        display: block;
      }
    }
  }
}
</style>
